package myJs.cps

import myJs.api.Api
import myJs.assets
import myJs.myPkg.Lightbox
import myJs.myPkg.jquery.$
import myJs.tool.Tool
import org.scalajs.dom.{FileList, FileReader, html}
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks.useState
import slinky.core.facade.React
import slinky.web.html._

import scala.concurrent.{Future, Promise}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import typings.csstype.csstypeStrings

import scala.scalajs.js.Date

/**
 * Created by yz on 21/1/2022
 */
@react object ImageSelectCp {

  case class Props(serverImages: List[String], images: List[String], removeImg: Int => Unit,
                   imagesAdd: List[String] => Unit, id: String, removeServerImg: Int => Unit)

  val component = FunctionalComponent[Props] { props =>

    val (isOpen, setIsOpen) = useState(false)
    val (photoIndex, setPhotoIndex) = useState(0)

    val inputRef = React.createRef[html.Input]

    object FTool {

      def openFile = () => {
        inputRef.current.click()
      }

      def viewImage = () => {
        val y = inputRef.current
        val fileOp = $(y).prop("files")
        fileOp.foreach { files =>
          val fileList = files.asInstanceOf[FileList]
          val fs = fileList.map { file =>
            val promise = Promise[String]()
            val reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onloadend = (e) => {
              val uri = reader.result.toString
              promise.success(uri)
            }
            promise.future
          }
          Future.sequence(fs).map { curUris =>
            props.imagesAdd(curUris.toList)
          }

        }

      }

      def preview(curI: Int) = () => {
        setPhotoIndex(curI)
        setIsOpen(true)
      }

      def closeF = () => {
        setIsOpen(false)
      }

      def nextF(nextIndex: Int) = () => {
        setPhotoIndex(nextIndex)
      }

      def prevF(preIndex: Int) = () => {
        setPhotoIndex(preIndex)
      }

      def removeImg(curI: Int) = () => {
        props.removeImg(curI)
      }

      def removeServerImg(curI: Int) = () => {
        props.removeServerImg(curI)
      }

    }

    val images = props.images

    div(style := Style(),
      props.serverImages.zipWithIndex.map { case (imageName, curI) =>
        val url = Tool.imageUrl(props.id, s"thumb_${imageName}")
        div(key := s"${curI}", style := STool.imgDiv,
          div(style := STool.img(url),
            onClick := FTool.preview(curI),
            className := "myImgDiv"
          ),
          label(style := STool.removeLabel,
            className := "btn-icon myLabel", onClick := FTool.removeServerImg(curI),
            i(style := Style(), className := "fa fa-remove myRemove")
          )
        )
      },
      images.zipWithIndex.map { case (uri, curI) =>
        val viewI = curI + props.serverImages.size
        div(key := s"${curI}", style := STool.imgDiv,
          div(style := STool.img(uri),
            onClick := FTool.preview(viewI),
            className := "myImgDiv"
          ),
          label(style := STool.removeLabel,
            className := "btn-icon myLabel", onClick := FTool.removeImg(curI),
            i(style := Style(), className := "fa fa-remove myRemove")
          )
        )
      },
      input(`type` := "file", style := Style(display = csstypeStrings.none), ref := inputRef, multiple,
        onChange := FTool.viewImage, accept := "image/png,image/jpeg"),

      div(style := STool.addImgDiv, onClick := FTool.openFile,
        div(style := STool.addImg)
      ),

      if (isOpen) {
        val serverUrls = props.serverImages.map { x =>
          Tool.imageUrl(props.id, x)
        }
        val totalImages = serverUrls ::: props.images
        val nextIndex = (photoIndex + 1) % totalImages.length
        val preIndex = (photoIndex + totalImages.length - 1) % totalImages.length
        Lightbox(mainSrc = totalImages(photoIndex), nextSrc = totalImages(nextIndex), prevSrc = totalImages(preIndex),
          imageTitle = s"${photoIndex + 1}/${totalImages.size}",
          onCloseRequest = FTool.closeF,
          onMoveNextRequest = FTool.nextF(nextIndex),
          onMovePrevRequest = FTool.prevF(preIndex)
        )()
      } else null

    )

  }

  object STool {

    val imgWidth = 150
    val imgHeight = 150

    val imgDiv = Style(backgroundRepeat = "no-repeat", backgroundSize = "cover",
      position = csstypeStrings.relative, display = csstypeStrings.`inline-block`, marginRight = 20)

    val addImgDiv = Style(backgroundRepeat = "no-repeat", backgroundSize = "cover",
      position = csstypeStrings.relative, display = csstypeStrings.`inline-block`, cursor = csstypeStrings.pointer)

    def img(uri: String) = Style(backgroundImage = s"url('${uri}')", backgroundRepeat = "no-repeat",
      backgroundSize = "cover", width = imgWidth, height = imgHeight, border = "3 px solid #fff",
      boxShadow = " 0 .1rem 1rem .25rem rgba(0,0,0,.05)", borderRadius = "0.475rem")

    val addImg = Style(backgroundImage = s"url('${Api.images}/addimg.png' )",
      backgroundRepeat = "no-repeat",
      backgroundSize = "cover", width = imgWidth, height = imgHeight, border = "3 px solid #fff",
      boxShadow = " 0 .1rem 1rem .25rem rgba(0,0,0,.05)", borderRadius = "0.475rem")

    val removeLabel = Style(left = "100%", top = 0, display = csstypeStrings.`inline-flex`, alignItems = csstypeStrings.center,
      justifyContent = csstypeStrings.center, position = csstypeStrings.absolute, borderRadius = "50%",
      boxShadow = " 0 .5rem 1.5rem .5rem rgba(0,0,0,.075)", transform = "translate(-50%,-50%)", width = 25,
      height = 25)

  }


}
